package logic;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * Saves objects to file, and load it from file.
 * @author Dmitry Kuznetsov <zendipy@gmail.com>
 * @version 1.0
 */

public class Serializator {
	
	/**
	 * Default constructor
	 */
	public Serializator(){
		
	}
	
	/**
	 * Save serializable object to file
	 * @param o				object to be serialized
	 * @param fileName		name of file
	 * @throws IOException	
	 */
	public void save(Serializable o, String fileName) throws IOException{
		FileOutputStream fos = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(fos);
		out.writeObject(o);
		out.flush();
		out.close();	
	}
	
	/**
	 * Save object to XML-file
	 * @param o				object to save
	 * @param fileName		name of an XML file
	 * @throws IOException
	 */
	public void saveToXML(Object o, String fileName) throws IOException{
		//TODO!!!! Doesn't work :(
		XMLEncoder e = new XMLEncoder(
                new BufferedOutputStream(
                    new FileOutputStream(fileName)));
		e.writeObject(o);
		e.close();
	}
	
	/**
	 * Load object form XML file
	 * @param fileName		name of XML file
	 * @return				loaded {@link Object}
	 * @throws IOException
	 */
	public Object loadFromXML(String fileName) throws IOException{
		// TODO!!!! Doesn't work :(
		XMLDecoder d = new XMLDecoder(
                new BufferedInputStream(
                    new FileInputStream(fileName)));
		Object result = d.readObject();
		d.close();
		return result;
	}
	
	/**
	 * Load object from file
	 * @param fileName					name of file to load
	 * @return							loaded {@link Object}
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public Object load(String fileName) throws IOException, ClassNotFoundException{	
		FileInputStream fis = new FileInputStream(fileName);
		ObjectInputStream in = new ObjectInputStream(fis);
		Object o = in.readObject();
		in.close();
		return o;
	}

}
